// pages/contract-detail/contract-detail.js
Page({
  data: {
    contractId: null,
    contract: null,
    loading: true,
    showSignModal: false,
    signatureData: '',
    agreementChecked: false
  },

  onLoad(options) {
    const contractId = options.id;
    if (contractId) {
      this.setData({ contractId });
      this.loadContractDetail();
    } else {
      wx.showToast({
        title: '合同不存在',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 加载合同详情
  loadContractDetail() {
    const token = wx.getStorageSync('token');
    if (!token) {
      this.showLoginPrompt();
      return;
    }

    wx.request({
      url: `http://localhost:8080/api/user/contracts/${this.data.contractId}`,
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.success) {
          this.setData({
            contract: res.data.data,
            loading: false
          });
        } else {
          this.showError('合同不存在');
        }
      },
      fail: () => {
        // 模拟数据
        const mockContract = {
          id: this.data.contractId,
          jobTitle: '前端开发工程师',
          jobId: 1,
          employerId: 1,
          employerName: '某科技公司',
          employerContact: '010-12345678',
          employerAddress: '北京市朝阳区中关村软件园A座',
          workerId: 1,
          workerName: '张三',
          workerPhone: '13800138000',
          workerIdCard: '110101199001011234',
          contractType: 'FULL_TIME',
          status: 'PENDING',
          startDate: '2024-01-15',
          endDate: '2024-07-15',
          workLocation: '北京市朝阳区中关村软件园',
          workTime: '周一至周五 9:00-18:00',
          salary: 12000,
          salaryType: 'MONTHLY',
          paymentMethod: 'BANK_TRANSFER',
          responsibilities: '1. 负责公司前端项目开发\n2. 参与产品需求分析\n3. 设计并实现用户界面\n4. 优化用户体验\n5. 配合后端开发完成项目',
          requirements: '1. 熟悉React、Vue等主流前端框架\n2. 具备良好的编程习惯\n3. 具备团队协作能力\n4. 有相关工作经验优先',
          benefits: '1. 五险一金\n2. 带薪年假\n3. 节日福利\n4. 培训机会\n5. 弹性工作时间',
          terms: '1. 双方应严格遵守合同条款\n2. 如需变更合同内容，需双方协商一致\n3. 合同期满自动终止\n4. 违约方应承担相应责任',
          createTime: '2024-01-08 10:00:00',
          signTime: null,
          contractUrl: null
        };
        
        this.setData({
          contract: mockContract,
          loading: false
        });
      }
    });
  },

  // 显示签署弹窗
  showSignModal() {
    if (this.data.contract.status !== 'PENDING') {
      wx.showToast({
        title: '合同状态不允许签署',
        icon: 'none'
      });
      return;
    }

    this.setData({
      showSignModal: true,
      signatureData: '',
      agreementChecked: false
    });
  },

  // 隐藏签署弹窗
  hideSignModal() {
    this.setData({
      showSignModal: false
    });
  },

  // 协议勾选
  onAgreementChange(e) {
    this.setData({
      agreementChecked: e.detail.value.length > 0
    });
  },

  // 签名输入
  onSignatureInput(e) {
    this.setData({
      signatureData: e.detail.value
    });
  },

  // 确认签署
  confirmSign() {
    if (!this.data.agreementChecked) {
      wx.showToast({
        title: '请先同意合同条款',
        icon: 'none'
      });
      return;
    }

    if (!this.data.signatureData.trim()) {
      wx.showToast({
        title: '请输入电子签名',
        icon: 'none'
      });
      return;
    }

    wx.showModal({
      title: '确认签署',
      content: '签署后将不可撤销，请确认合同内容无误',
      success: (res) => {
        if (res.confirm) {
          this.performSign();
        }
      }
    });
  },

  // 执行签署
  performSign() {
    const token = wx.getStorageSync('token');

    wx.showLoading({
      title: '签署中...'
    });

    wx.request({
      url: `http://localhost:8080/api/user/contracts/${this.data.contractId}/sign`,
      method: 'PUT',
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      data: {
        signature: this.data.signatureData
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data.success) {
          wx.showToast({
            title: '签署成功',
            icon: 'success'
          });
          this.updateContractStatus('SIGNED');
          this.hideSignModal();
        } else {
          wx.showToast({
            title: res.data.message || '签署失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '签署成功',
          icon: 'success'
        });
        this.updateContractStatus('SIGNED');
        this.hideSignModal();
      }
    });
  },

  // 更新合同状态
  updateContractStatus(newStatus) {
    const contract = { ...this.data.contract };
    contract.status = newStatus;
    contract.signTime = new Date().toLocaleString();
    this.setData({ contract });
  },

  // 下载合同
  downloadContract() {
    if (this.data.contract.status === 'PENDING') {
      wx.showToast({
        title: '请先签署合同',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '下载中...'
    });

    // 模拟下载
    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({
        title: '下载成功',
        icon: 'success'
      });
    }, 1500);
  },

  // 联系雇主
  contactEmployer() {
    if (!this.data.contract || !this.data.contract.employerContact) {
      wx.showToast({
        title: '无法获取联系方式',
        icon: 'none'
      });
      return;
    }

    wx.showActionSheet({
      itemList: ['拨打电话', '发送短信'],
      success: (res) => {
        if (res.tapIndex === 0) {
          wx.makePhoneCall({
            phoneNumber: this.data.contract.employerContact
          });
        } else if (res.tapIndex === 1) {
          // 发送短信功能
          wx.showToast({
            title: '短信功能开发中',
            icon: 'none'
          });
        }
      }
    });
  },

  // 查看相关岗位
  viewJob() {
    if (this.data.contract && this.data.contract.jobId) {
      wx.navigateTo({
        url: `/pages/job-detail/job-detail?id=${this.data.contract.jobId}`
      });
    }
  },

  // 显示登录提示
  showLoginPrompt() {
    wx.showModal({
      title: '未登录',
      content: '请先登录后查看合同详情',
      confirmText: '去登录',
      success: (res) => {
        if (res.confirm) {
          wx.switchTab({
            url: '/pages/profile/profile'
          });
        } else {
          wx.navigateBack();
        }
      }
    });
  },

  // 显示错误信息
  showError(message) {
    wx.showToast({
      title: message,
      icon: 'none'
    });
    setTimeout(() => {
      wx.navigateBack();
    }, 1500);
  },

  // 格式化合同类型
  formatContractType(type) {
    const typeMap = {
      'FULL_TIME': '全职',
      'PART_TIME': '兼职',
      'TEMPORARY': '临时工',
      'INTERNSHIP': '实习'
    };
    return typeMap[type] || type;
  },

  // 格式化合同状态
  formatContractStatus(status) {
    const statusMap = {
      'PENDING': '待签署',
      'SIGNED': '已签署',
      'EXECUTING': '执行中',
      'COMPLETED': '已完成',
      'TERMINATED': '已终止'
    };
    return statusMap[status] || status;
  },

  // 格式化薪资
  formatSalary(salary, salaryType) {
    let unit = '';
    switch (salaryType) {
      case 'HOURLY': unit = '/时'; break;
      case 'DAILY': unit = '/天'; break;
      case 'MONTHLY': unit = '/月'; break;
      default: unit = '';
    }
    return `${salary}元${unit}`;
  },

  // 格式化支付方式
  formatPaymentMethod(method) {
    const methodMap = {
      'CASH': '现金',
      'BANK_TRANSFER': '银行转账',
      'ALIPAY': '支付宝',
      'WECHAT_PAY': '微信支付'
    };
    return methodMap[method] || method;
  },

  // 获取状态颜色
  getStatusColor(status) {
    const colorMap = {
      'PENDING': '#fa8c16',
      'SIGNED': '#1890ff',
      'EXECUTING': '#52c41a',
      'COMPLETED': '#722ed1',
      'TERMINATED': '#f5222d'
    };
    return colorMap[status] || '#666';
  }
});
